// pages/goods_detail/index.js
/* 发送请求 获取数据 
点击轮播图 预览大图片
点击加入购物车 获取缓存中数据数组格式
*/
import { request } from '../../request/index.js';
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj:{},
    isCollect:false
  },
  // 商品对象
  GoodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages =  getCurrentPages();
    let currentPage=pages[pages.length-1];
    let options=currentPage.options;
    const {goods_id} = options;
    // console.log(goods_id);
    this.getGoodsDetail(goods_id);
    
  },
  // 获取商品详情数据
  async getGoodsDetail(goods_id){
    const goodsObj = await request({url:"/goods/detail",data:{goods_id}});
    // console.log(goodsObj);
    this.GoodsInfo=goodsObj;
    let collect=wx.getStorageSync("collect")||[];
    let isCollect=collect.some(v=>v.goods_id===this.GoodsInfo.goods_id);
    this.setData({
      goodsObj:{
        goods_name:goodsObj.goods_name,
        goods_price:goodsObj.goods_price,
        // iphone部分手机不支持识别webp格式 1.webp=>1.jpg
        goods_introduce:goodsObj.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics:goodsObj.pics
      },
      isCollect
    })
  },
  // 放大预览轮播图
  handlePreviewImage(e){
    const urls=this.GoodsInfo.pics.map(v=>v.pics_mid);
    // 接受传递过来的图片的url
    const current=e.currentTarget.dataset.url;
    wx.previewImage({
      current,
      urls
    })
      
  },
  // 点击加入购物车
  handleCartAdd(){
    // 1、获取缓存中购物车数组
    let cart=wx.getStorageSync("cart")||[];
      // 2、判断商品对象是否存在购物车数组中
    let index=cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if(index===-1){
      // 3 不存在
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push(this.GoodsInfo);
    }else{
      // 4 存在
      cart[index].num++;
    }
    // 5把购物车重新添加回缓存中
    wx.setStorageSync("cart",cart);
    // 6、弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true
    })
    console.log(this.GoodsInfo);
  },
  handleCollect(){
    let isCollect=false;
    let collect=wx.getStorageSync("collect")||[];
    let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if(index!==-1){
      collect.splice(index,1);
      isCollect=false;
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        mask: true,
      });
        
    }else{
      collect.push(this.GoodsInfo);
      isCollect=true;
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        mask: true,
      });
    }
    wx.setStorageSync("collect",collect);
    this.setData({
      isCollect
    })
  }
})